<template>
    <div class="div_box">

        <div class="div_left">
            <div style="position: relative;width: 100%;">

                <!--视频组件-->
                <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :options="playerOptions">
                </video-player>
                <div class="slot_tips_h5player" v-show="playerflag == 1 || playerflag == 3">
                    <i class="el-icon-video-pause" v-show="playerflag == 1"></i>
                    <span v-show="playerflag == 1">暂停</span>
                    <i class="el-icon-loading" v-show="playerflag == 3 && flag"></i>
                    <span v-show="playerflag == 3 && flag">正在缓冲...</span>
                </div>
            </div>

            <div class="webplayer_menu">
                <i class="el-icon-video-play" id="playerResumeButton" v-show="playerflag == 1 || playerflag == 3"></i>
                <i class="el-icon-video-pause" id="playerPauseButton" style="color: #7367F0;" v-show="playerflag == 2"></i>
            </div>

            <div class="webplayer">
                <div>
                    <i class="iconfont huatong" id="audioTalkStop" style="color: #7367F0;" v-show="!audio"></i>
                        <i class="iconfont huatong1" id="audioTalkStart"  v-show="audio"></i>
                        对讲
                </div>
                      <div> 
                        <i class="iconfont guanbiyinliang" id="playerVolume1" v-show="!playerVolumeflag"></i>
                        <i class="iconfont zengdayinliang" id="playerVolume" v-show="playerVolumeflag" style="color: #7367F0;"></i>
                        声音
                      </div>
            </div>
            

            <!-- 控制台 -->
            <div class="direction">
                <div class="circle">
                    <div class="top">
                        <i class="iconfont sanjiaodown"></i>
                    </div>
                    <div class="right">
                        <i class="iconfont sanjiaoright"></i>
                    </div>
                    <div class="left">
                        <i class="iconfont sanjiaoleft"></i>
                    </div>
                    <div class="bottom">
                        <i class="iconfont sanjiaodown"></i>
                    </div>
                    <div class="middle">控制台</div>
                </div>
            </div>
            
        </div>
        

        <div class="info" style="height: calc(100vh - 480rpx - 30rpx);">
            <div class="title">
               设备信息
            </div>
            <div class="msg">
                <span class="label">设备状态：</span>
                <span v-if="deviceInfo.online === 1" style="color:#41d4b5">在线</span>
                <span v-else style="color:#f66968">离线</span>
            </div>
            <div class="msg">
                <span class="label">设备编码：</span>
                <span >{{deviceInfo.imei}}</span>
            </div>
            <div class="msg">
                <span class="label">安装地址：</span>
                <span >{{deviceInfo.spaceName}}</span>
            </div>
        </div>

        <!-- h5播放器  视频流 -->
        <!-- <video id="my_video_1" class="video-js vjs-default-skin" width="100%" height="100%"
                    controls preload="none" poster='http://video-js.zencoder.com/oceans-clip.jpg'
                    data-setup='{ "aspectRatio":"640:267", "playbackRates": [1, 1.5, 2] }'>
                    <source src="https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8" type='application/x-mpegURL' />
            </video> -->

    </div>
</template>

<script>
// axios全局配置，允许跨域带cookie
// axios.defaults.withCredentials = true;

import videojs from "video.js";
import "vue-video-player/src/custom-theme.css";
import "video.js/dist/video-js.css";
import { videoPlayer } from "vue-video-player";
import {
    reqCameraget,
    reqCameralogin,
    reqCamerainfo,
} from "@api/api.js";
// import {
//     reqDeptList,
//     reqDeviceList,
//     reqCameraUrl,
// } from "@api/apicamera.js";
import asc from "@utils/asc.js"; //前端加解密

export default {
    props: {

    },
    components: {
        videoPlayer,
    },
    data() {
        return {
            // 视频控制设置
            playerOptions: {
                playbackRates: [0.7, 1.0, 1.5, 2.0], // 可选的播放速度
                autoplay: true, // 如果为true,浏览器准备好时开始回放。
                muted: false, // 默认情况下将会消除任何音频。
                loop: false, // 是否视频一结束就重新开始。
                preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                language: "zh-CN",
                aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                sources: [
                    {
                        // type: "video/mp4", // 类型
                        type: "application/x-mpegURL",
                        // src: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", // url地址
                        src: "", // url地址
                    },
                ],
                poster: "", // 封面地址
                width: "1000", //document.documentElement.clientWidth 播放器宽度
                height: 150,
                notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
                controlBar: {
                    timeDivider: true, // 当前时间和持续时间的分隔符
                    durationDisplay: true, // 显示持续时间
                    remainingTimeDisplay: true, // 是否显示剩余时间功能
                    fullscreenToggle: true, // 是否显示全屏按钮
                    volumeControl: true, // 声音控制键
                    playToggle: true, // 暂停和播放键
                    progressControl: true, // 进度条
                },
            },
            src: "",
            deviceInfo: {},
            logoindata: {},
            Camerainfo: {},
            userInfo: {
                username: "",
                password: "",
            },
            webPlayer: null,
            playerflag: 3,// 暂停1 播放2 缓冲3
            flag: false,//无MAC地址
            playerVolumeflag: true,//声音
            audio: true,//麦克风
        };
    },
    computed: {},
    watch: {},
    methods: {
        //获取摄像头账号密码
        async Cameraget() {
            const res = await reqCameraget()
            this.userInfo.username = res.data.rows.username;
            this.userInfo.password = res.data.rows.password;
        },
        //摄像头账号登录
        async Cameralogin() {
            // 加密
            const res = await reqCameralogin(asc.encryption({
                data: this.userInfo,
                key: 'thank,cloudstore', //加密用的key
                param: ['password'],
            }))
            //    console.log(res);
            this.logoindata = res.data.row
        },
        //获取摄像头设备详情
        async reqCamerainfo() {
            const res = await reqCamerainfo({
                deviceMac: this.deviceInfo.deviceMac,
                token: this.logoindata.access_token
            })
            //    console.log(res);
            this.Camerainfo = res.data.row;
        },
        // 初始化播放器
        initWebPlayer() {
            // console.log(this.Camerainfo);
            if (this.Camerainfo == null || this.Camerainfo == '') {
                this.flag = false;
                this.$toast('设备MAC地址不正确')
                return
            } else {
                this.flag = true;
            }
            // console.log(this.Camerainfo);
            this.webPlayer = new WebPlayer({
                productKey: '9fea0cdb-0ca',
                channelNo: '', //NVR设备传入通道号，IPC设备传入 ''
                token: this.Camerainfo.token,
                deviceId: this.Camerainfo.deviceMac,
                channel: '720p',
                playerContainer: '.video-player',
                hasAudio: true,
                hasBaseUI: false,
                platform: 'bluramsBZ',
                runtimeEnv: 'pro',
                // isSDCardPlayback: true //当是SD卡回放时传入
            });
            // console.log(this.webPlayer);
            let isPlayInit = false;
            this.webPlayer.on(WebPlayer.WebPlayerEvents.PLAYER_INIT, async () => {
                //初始化成功
                // console.log('初始化成功',this.webPlayer);
                let deviceStatus = this.webPlayer.getCanPlayStatus();//获取设备可播放状态
                //设备在线且设备开关打开
                if (deviceStatus.onlineStatus && deviceStatus.deviceStatus) {
                    this.webPlayer.play();//播放直播
                } else {
                    //TODO 显示设备离线或关闭状态UI
                }
                isPlayInit = true;
            });
            this.webPlayer.on(WebPlayer.WebPlayerEvents.PLAYER_INIT_ERROR, () => {
                console.log('初始化失败');//初始化失败
            });

            //点击暂停按钮
            document.querySelector('#playerPauseButton').addEventListener('click', () => {
                if (!isPlayInit) return;
                this.webPlayer.pause();//播放暂停
            }, false);

            //点击恢复播放按钮
            document.querySelector('#playerResumeButton').addEventListener('click', () => {
                if (!isPlayInit) return;
                this.webPlayer.resume();//恢复播放
            }, false);

            this.webPlayer.on(WebPlayer.WebPlayerEvents.PLAYER_BUFFER, () => {
                //正在缓冲视频，显示加载状态UI和其它UI操作
                // console.log('正在缓冲视频');
                this.playerflag = 3;
            });

            //开始播放，从非播放状态到播放状态时触发,网络不佳时，频繁loading时会多次触发
            this.webPlayer.on(WebPlayer.WebPlayerEvents.PLAYER_PLAY, () => {
                //开始播放视频，隐藏加载状态、暂停状态等UI
                // console.log('开始播放视频');
                this.playerflag = 2;
            });

            this.webPlayer.on(WebPlayer.WebPlayerEvents.PLAYER_PAUSE, () => {
                //播放暂停，显示暂停状态UI
                // console.log('播放暂停');
                this.playerflag = 1;
            });


            //打开音量
            document.querySelector('#playerVolume1').addEventListener('click', (e) => {
                if (!isPlayInit) return;
                var value = 1; // 取值[0-1]
                this.webPlayer.setVolume(value);
                this.playerVolumeflag = true;
            }, false)

            //关闭声音
            document.querySelector('#playerVolume').addEventListener('click', (e) => {
                if (!isPlayInit) return;
                var value = 0; // 取值[0-1]
                this.webPlayer.setVolume(value);
                this.playerVolumeflag = false;
            }, false)


            // 开始对讲
            let canAudioTalk = false;
            document.querySelector('#audioTalkStart').addEventListener('click', (e) => {
                let isSupportAudioTalk = WebPlayer.isSupportAudioTalk();
                // if (!isSupportAudioTalk) return this.$modal.notifyWarning('暂不支持语音对讲');
                if (!isPlayInit || this.webPlayer.isRecord()) return;
                this.webPlayer.initTalk((error) => {
                    // if (!error) {
                        canAudioTalk = true;
                        this.webPlayer.startTalk();//开始对讲
                        this.audio = false;
                        return;
                    // }
                    // this.$modal.notifyWarning('请确认已打开系统麦克风权限或者浏览器麦克风权限！');
                    // console.error(error, '12312312');
                })
            }, false);

            //结束通话
            document.querySelector('#audioTalkStop').addEventListener('click', (e) => {
                canAudioTalk && this.webPlayer.stopTalk()
                this.audio = true;
            }, false);


            //截屏
            document.querySelector('#playerScreenShot').addEventListener('click', (e) => {
                if (!isPlayInit) return;
                const isOrigin = true;
                //截屏，safari浏览器不支持该截屏功能
                let base64Image = this.webPlayer.screenShot(isOrigin);
                //在<img/>中显示
                if (base64Image) {
                    // console.log(base64Image);
                    this.phoneDown(base64Image, `直播截图`)
                }
            }, false);

            // 进入全屏
            document.querySelector('#fullScreen').addEventListener('click', (e) => {
                WebPlayer.requestFullScreen(document.querySelector('.video-player'));
            }, false);

        },
        // 销毁播放器实例
        // destroy(){
        //     // console.log(this.webPlayer)
        //     if(this.webPlayer!=null){
        //           this.webPlayer.destroy();
        //     }
        //     this.playerflag=3;
        //     this.playerVolumeflag=true//声音
        //     this.audio=true//麦克风
        //     this. playerOptions= {
        //         playbackRates: [0.7, 1.0, 1.5, 2.0], // 可选的播放速度
        //         autoplay: true, // 如果为true,浏览器准备好时开始回放。
        //         muted: false, // 默认情况下将会消除任何音频。
        //         loop: false, // 是否视频一结束就重新开始。
        //         preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        //         language: "zh-CN",
        //         aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        //         fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        //         sources: [
        //             {
        //                 type: "video/mp4", // 类型
        //                 // src: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", // url地址
        //                 src: "", // url地址
        //             },
        //         ],
        //         poster: "", // 封面地址
        //         width: "1000", //document.documentElement.clientWidth 播放器宽度
        //         height: 100,
        //         notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        //         controlBar: {
        //             timeDivider: true, // 当前时间和持续时间的分隔符
        //             durationDisplay: true, // 显示持续时间
        //             remainingTimeDisplay: true, // 是否显示剩余时间功能
        //             fullscreenToggle: true, // 是否显示全屏按钮
        //             volumeControl: true, // 声音控制键
        //             playToggle: true, // 暂停和播放键
        //             progressControl: true, // 进度条
        //         },
        //     }
        // },
        // 下载图片
        phoneDown(imgsrc, name) {
            //下载图片地址和图片名
            let image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                let canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                let context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                let url = canvas.toDataURL('image/png') //得到图片的base64编码数据
                let a = document.createElement('a') // 生成一个a元素
                let event = new MouseEvent('click') // 创建一个单击事件
                a.download = name || 'photo' // 设置图片名称
                a.href = url // 将生成的URL设置为a.href属性
                a.dispatchEvent(event) // 触发a的单击事件
            }
            image.src = imgsrc
        },

        //   // 获取设备列表
        //   async DeviceList(){
        //     const res = await reqDeviceList({
        //         token: this.logoindata.access_token,
        //         deviceMac:"0011040682a7",
        //         current:1,
        //         size:10
        //     })
        //        console.log(res);
        //        this.deviceId=res.data.row[0].deviceId
        // },
        // // 获取设备播放url地址
        // async CameraUrl(){
        //     const res = await reqCameraUrl({
        //         deviceType: 0,
        //         token: this.logoindata.access_token,
        //         schema:0,
        //         deviceId:this.deviceId,
        //         type:0
        //     })
        //     //    console.log(res);
        //     //    this.playerOptions.sources.src=res.data.row.url;
        //     //    this.src=res.data.row.url;
        //     //    this.src='https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8'
        //     //    console.log(this.src);
        //     // this.Camerainfo = res.data.row;
        // },
        // 在链接的 h5 页面使用正则解析出小程序 src 中所带的一些参数和值
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        }

    },
    async created() {
        // console.log(window.location.search.substr(1))
        
        // console.log(this.deviceInfo);

    },
    async mounted() {
        this.deviceInfo = JSON.parse(this.getQueryString("deviceInfo")) || "0";

        await this.Cameraget()//获取摄像头账号密码
        await this.Cameralogin() //摄像头账号登录
        await this.reqCamerainfo()//获取摄像头设备详情
        await this.initWebPlayer()

        // await this.Cameraget()//获取摄像头账号密码
        // await this.Cameralogin() //摄像头账号登录
        // await this.DeviceList()// 获取设备列表
        // await this.CameraUrl() // 获取设备播放url地址

        //     let { search } = window.location;
        //     console.log(search);
        // search = decodeURI(search);
        // // this.sn = search.substr(5, 8); //
        // this.sn = search.substr(4, 8); //变量--mini

        //     document.addEventListener('visibilitychange',function(e){
        //     //   console.log(document.visibilityState);
        //   let state = document.visibilityState
        //     if(state == 'hidden'){
        //         console.log(document.visibilityState,'用户离开了');
        //     }
        //     if(state == 'visible'){
        //         console.log(document.visibilityState,'回来了');
        //     }
        //     });
    },
};
</script>


<style lang="less" scoped>
.div_box {
    overflow: auto;
    width: 100%;
    height: 100%;
    .div_left {
        width: 100%;

        // display: flex;
        // flex-direction: column;
        // align-items: center;
        .webplayer_menu {
            background: #F7F7F7;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 2.5rem;
            box-sizing: border-box;

            i {
                font-size: 30px;
            }
        }

        .webplayer{
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0.5rem 0;
            box-sizing: border-box;
            font-size: 0.6rem;
            >div{
                width: 50%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }
            i {
                font-size: 30px;
            }
        }

        .slot_tips_h5player {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            margin: auto;
            background: rgba(0, 0, 0, 0.5);
            font-size: 14px;
            display: flex;
            color: rgba(255, 255, 255, 0.8) !important;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            i {
                font-size: 60px;
            }

            span {
                margin: 7px;
                font-size: 16px;
            }
        }
    }

    .info{
        background-color: #F7F7F7;
        width: 92%;
        margin: auto;
        border-radius: 0.6rem 0.6rem 0 0;
        padding: 1rem;
        box-sizing: border-box;
        font-size: 0.95rem;
        color: #000;
        line-height: 2rem;
        .title{
            font-weight: 700;
            
        }
        .label{
            color: #595959;
        }
    }

}

::v-deep .video-player {
    // width: 100vw !important;
    width: 100% !important;
}

.video-ctrl-box {
    width: 180px;
    height: 180px;
    border-radius: 50%;
    background: @primaryBgcolor3;
    // position: relative;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);

    .ctrl-circle {
        position: absolute;
        width: 70px;
        height: 70px;
        background: @primaryBgcolor4;
        border-radius: 50%;
        left: 50%;
        top: 50%;
        transform: translateY(-50%) translateX(-50%);
        display: flex;
        justify-content: center;
        align-items: center;
        color: @primaryFFFColor3;
    }

    i {
        cursor: pointer;
        position: absolute;
        color: @primaryFFFColor4;

        &:active {
            color: #50E3C2;
        }
    }



    .el-icon-caret-left {
        top: 44%;
        left: 27px;
        transform: translateX(-50%) scale(0.8);
    }

    .el-icon-caret-right {
        top: 44%;
        right: -3px;
        transform: translateX(-50%) scale(0.8);
    }

    .el-icon-caret-top {
        left: 50%;
        transform: translateX(-50%) translateY(12px) scale(0.8);
    }

    .el-icon-caret-bottom {
        left: 50%;
        bottom: 39px;
        transform: translateX(-50%) translateY(90%) scale(0.8);
    }
}

.direction {
    position: relative;
    /* padding-top: 10vw; */
    margin-bottom: 5vw;
    width: 100vw;
    height: 30vh;
    font-size: 0.6rem;
    // background-color: #F8F8F8;
}

.direction .circle {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 45vw;
    height: 45vw;
    background-color: #EFEFEF;
    border-radius: 50%;
}

.direction .circle .middle {
    background-color: #FFFFFF;
    border-radius: 50%;
    width: 18vw;
    height: 18vw;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    justify-content: center;
    align-items: center;
    color: #595959;
    font-size: 30rpx;
}

.direction .circle span {
    color: #878787;
}

.direction .circle .top {
    position: absolute;
    left: 50%;
    top: 5%;
    transform: translateX(-50%) rotate(180deg);
}

.direction .circle .bottom {
    position: absolute;
    left: 50%;
    bottom: 5%;
    transform: translateX(-50%);
}

.direction .circle .right {
    position: absolute;
    right: 5%;
    top: 50%;
    transform: translateY(-50%);
}

.direction .circle .left {
    position: absolute;
    left: 5%;
    top: 50%;
    transform: translateY(-50%);
}</style>